﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Dynamic;
using System.Transactions;
using PagedList;
using Sovigaz.DataProvider;
using Utilities;

namespace Sovigaz.Permission.Repositories
{
    public class OrderLineRepository : GenericRepository
    {
        public OrderLineRepository()
            : base("OrderLineID")
        {
        }

        public ICollection<OrderLine> OrderLines { get; set; }

        public void Delete(int id)
        {
            var item = GetByID(id);
            if (item != null)
                item.IsDeleted = true;

            _context.SaveChanges();
        }

        public void Delete(string[] idArr)
        {
            foreach (var id in idArr)
            {
                var item = GetByID(ConvertUtility.IntParse(id));
                if (item != null)
                    item.IsDeleted = true;
            }

            _context.SaveChanges();
        }

        public int Update(OrderLine orderline)
        {
            var update = new OrderLine();

            using (var scope = new TransactionScope())
            {
                if (orderline.OrderLineID > 0)
                {
                    update = GetByID(orderline.OrderLineID);
                    if (!Utility.ArrayEqual(update.Tstamp, orderline.Tstamp))
                        throw ExceptionHelper.CreateHttpResponseException("Dữ liệu đã bị cập nhật bởi người sử dụng khác.");
                }
                if (update.OrderLineID <= 0)
                    _context.OrderLines.Add(update);

                update.OrderLineID = orderline.OrderLineID;
                update.OrderID = orderline.OrderID;
                update.CategoryID = orderline.CategoryID;
                update.Size = orderline.Size;
                update.Capacity = orderline.Capacity;
                update.OrderQty = orderline.OrderQty;
                update.Description = orderline.Description;
                _context.SaveChanges();

                scope.Complete();
            }

            _context.Entry(update).Reload();

            return update.OrderLineID;
        }

        public void Update(ICollection<OrderLine> orderLines, int OrderID, TransactionScope transactionScope)
        {
            foreach (OrderLine orderline in orderLines)
            {
                var updateOrderline = new OrderLine();
                orderline.OrderID = OrderID;
                if (orderline.OrderLineID > 0)
                    updateOrderline = GetByID(orderline.OrderLineID);
                updateOrderline.OrderID = OrderID;
                updateOrderline.OrderLineID = orderline.OrderLineID;
                updateOrderline.OrderQty = orderline.OrderQty;
                updateOrderline.Size = orderline.Size;
                updateOrderline.Capacity = orderline.Capacity;
                updateOrderline.CategoryID = orderline.CategoryID;
                updateOrderline.Description = orderline.Description;

                if (updateOrderline.OrderLineID <= 0)
                    _context.OrderLines.Add(updateOrderline);
                _context.SaveChanges();
                _context.Entry(updateOrderline).Reload();
            }
        }

        public OrderLine GetByID(int id)
        {
            return _context.OrderLines.FirstOrDefault(p => p.OrderLineID == id && !p.IsDeleted);
        }

        public OrderLineRepository GetList(string whereClause, string orderBy, string orderDirection, int pageNumber)
        {
            var orderLines = _context.OrderLines.Where(whereClause)
                .OrderBy(String.Format("{0} {1}", orderBy.Trim(), orderDirection.Trim()))
                .ToPagedList(pageNumber, DefaultPageSize);

            TotalItemCount = orderLines.TotalItemCount;
            TotalItemOnPage = orderLines.Count;
            PageCount = orderLines.PageCount;
            PageNumber = orderLines.PageNumber;
            OrderLines = orderLines.ToList();

            return this;
        }

        public List<OrderLine> GetList()
        {
            List<OrderLine> list = _context.OrderLines.Where(p => !p.IsDeleted).OrderBy(p => p.OrderLineID).ToList();
            return list;
        }

        public List<OrderLine> GetList(Order order, List<int> orderLineIds, List<int> planQtys)
        {
            List<OrderLine> list = _context.OrderLines.Where(p => !p.IsDeleted && p.OrderID == order.OrderID).ToList();
            List<OrderLine> result = new List<OrderLine>();
            foreach (var orderLine in list)
            {
                orderLine.OrderRemainQty = orderLine.OrderQty - GetTotalPlanQty(orderLine.OrderLineID);
                orderLine.OrderCode = _context.Orders.FirstOrDefault(o => o.OrderID == orderLine.OrderID).OrderCode;
                orderLine.CategoryName = _context.Categories.FirstOrDefault(c => c.CategoryID == orderLine.CategoryID).CategoryName;
                orderLine.TC=_context.Products.Count(p=>p.CategoryID==orderLine.CategoryID && p.Size==orderLine.Size && p.OwnerID == order.PartnerID && p.PartnerID==1);
                if (orderLineIds.Contains(orderLine.OrderLineID)) orderLine.OrderRemainQty += planQtys[orderLineIds.IndexOf(orderLine.OrderLineID)];
                if (orderLine.OrderRemainQty > 0) result.Add(orderLine);
            }
            list.Clear();
            return result;
        }

        public List<OrderLine> GetList(int? OrderID)
        {
            if (OrderID.HasValue && OrderID > 0)
                return _context.OrderLines.Where(p => !p.IsDeleted && p.OrderID == OrderID).OrderBy(p => p.OrderLineID).ToList();
            else return new List<OrderLine>();
        }

        public int GetTotalPlanQty(int orderLineID)
        {
            return _context.DeliveryPlanLines.Where(d => d.OrderLineID == orderLineID && !d.IsDeleted).Sum(d => (int?)d.PlanQty) ?? 0;
        }

        public void DeleteByOrderID(int id)
        {
            List<OrderLine> list = _context.OrderLines.Where(o => o.OrderID == id).ToList() as List<OrderLine>;
            foreach (var item in list) _context.OrderLines.Remove(item);
            _context.SaveChanges();
        }

    }
}
